import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class MessageEncoder extends MessageToByteEncoder<IMessage> {
    @Override
    protected void encode(ChannelHandlerContext ctx, IMessage iMessage, ByteBuf out) throws Exception {
        if (!iMessage.getType().equals(MessageTypeEnum.EMPTY)) {
            out.writeByte(iMessage.getType().getType());
        }
        // 写入发送人
        int writeIndex = out.writerIndex();
        out.writeInt(0);
        int length = 0;
        if (null != iMessage.getFrom()) {
            length = ByteBufUtil.writeUtf8(out, iMessage.getFrom());
            out.setInt(writeIndex, length);
        }
        // 写入消息接收人
        writeIndex = out.writerIndex();
        out.writeInt(0);
        if (null != iMessage.getTo()) {
            length = ByteBufUtil.writeUtf8(out, iMessage.getTo());
            out.setInt(writeIndex, length);
        }
        // 写入消息体
        writeIndex = out.writerIndex();
        out.writeInt(0);
        if (null != iMessage.getBody()) {
            length = ByteBufUtil.writeUtf8(out, iMessage.getBody());
            out.setInt(writeIndex, length);
        }
    }
}
